import { defineComponent, onMounted, ref, onBeforeUnmount, watch, VNode } from "vue";


import MainNodeProcessWrap from '@src/modules/trigger/components/ProcessNodeChart/components/MainNodeProcessWrap'
/* enum */
import { TriggerType } from '@src/modules/trigger/model/enum/index.ts'
import { NodeTypeEnum } from '@src/modules/trigger/model/enum/index.ts'
import { useState, useCurrentInstance } from '@src/modules/trigger/hooks/useVC'
import type {ProcessNodeListItem} from '@src/modules/trigger/model/interface/index.ts'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* type */
import type { deleteMode } from '@src/modules/trigger/model/type/index.ts'

/* utils */
import _ from 'lodash'
import { uuid } from '@src/util/lang/string';
import state from '@src/modules/trigger/view/setting/util/state.js'
import {convertProcessCanvasDataForServer, convertServerDataForProcessCanvas} from '@src/modules/trigger/utils/convert.ts'
import '@src/modules/trigger/components/ProcessNodeChart/style/wrap.scss'
import { message } from '@src/util/message'
import { runVail, validatedResult, validateStartNode } from '@src/modules/trigger/utils/validate.ts'
import { findComponentDownward, findComponentUpward } from '@src/util/assist'
import { openAccurateTab } from '@src/util/platform'
import platform from '@src/platform';
import { codeGray } from '@src/modules/trigger/view/setting/util/codeGray.js'
import { compatibility } from '@src/modules/trigger/utils/compatibility.ts'
/* hooks */
import { getNodeType } from '@src/modules/trigger/utils/index.ts'
/* model */
import { TriggerFlowData } from '@src/modules/trigger/model'
/* http */
import{ createTrigger, getTriggerInfo, editTrigger }  from '@src/modules/trigger/api/trigger.js'

export default defineComponent({
    name: TriggerType.triggerDesignProcessNodeChat,
    props: {
        triggerId: {
            type: String,
            default: ''
        },
        loading: {
            type: Boolean,
            default: false
        }
    },
    emit: ['loading'],
    setup(props, { emit }) {
        const startUuid = uuid()
        const executeUuid = uuid()
        
        const [chartList, setChartList] = useState<ProcessNodeListItem[]>([{
            "type": NodeTypeEnum.START_NODE,
            "name":  "",
            "content": "",
            "children": [],
            "uniqueId": startUuid,
            "id": '',
            "options": {},
            "parentNode": null
        }])
        
        
        const [currentCtx, setData] = useCurrentInstance()

        const serverData = ref({}) // 后端结构数据用于前端数据结构转换函数中

        /**
         * @description 获取新建灰度
         */
        const getCreateGray = () => {
            if (props.triggerId) return
            // 如果是新建走下面逻辑
            emit('loading', true)
            codeGray().then(res => {
                setStateGray(res)
                emit('loading', false)
            })
            .catch(error => {
                console.error(error)
            })
        }
        getCreateGray()

        /**
         * @description 触发器数据转前端数据处理函数
         */
        const getTriggerInfoFront = async () => {
            try {
                emit('loading', true)
                const [res, grayRes] = await Promise.all([getTriggerInfo({ triggerId: props.triggerId}), codeGray()])
                if (!res.success) {
                    message.error(res.message)
                    return
                }
                if (!res.data) return
                setStateGray(grayRes)
                serverData.value = res.data
                setExecuteWay(res.data)
                setChartListData(convertServerDataForProcessCanvas(res.data as TriggerFlowData))
                emit('loading', false)
                console.log(convertServerDataForProcessCanvas(res.data))
            } catch (error) {
                console.error(error)
            }
            
        }

        /**
         * @description 设置触发器灰度
         * @param grayData 
         */
        const setStateGray = (gray: boolean) => {
            currentCtx.$set(state, 'trigger_code_gray', gray)
        }

        /**
         * @description 重新赋值树形结构数据
         * @param data 
         */
        function setChartListData(data: any) {
            if (!data) return
            setChartList(data) // 设置值
            addEndNode() // 添加结束节点
        }

        /**
         * @description 编辑情况下根据后端获取触发方式和名称
         * @param data 执行方式
         */
        function setExecuteWay(data: any) {
            state.executeWay = data.executeWay
            // @ts-ignore
            currentCtx.$set(state.currentTriggerInfo, 'name', data.name)
        }

        // 如果当前存在triggerId就获取详情
        watch(() => props.triggerId, async (newVal) => {
            if (newVal) {
                await getTriggerInfoFront()
                // 编辑进入新页面之后校验一下数据
                validateHandler()
            }
        }, { immediate: true })

        // 侦听当如果修改了开始节点的应用和对象，这将会将开始节点下面的子节点数据清空
        watch([
            () => chartList.value[0]?.options?.appId,
            () => chartList.value[0]?.options?.apiId,
        ], ([newAppId, newApiId], [oldAppId, oldApiId]) => {
            // console.log(newAppId, oldAppId)
            // console.log(newApiId, oldApiId)
            // 新建时：如果当前元素之前已经更改且新值不等于旧值 重新清空子节点数据
            if (
                (oldAppId && newAppId && newAppId !== oldAppId) 
                || (oldApiId && newApiId && oldApiId !== newApiId)
            ) {
                chartList.value[0].children = []
            }
        }, { immediate: true })
        /**
         * 处理弹窗添加节点逻辑功能函数
         * @param node 当前节点信息
         * @param newNode 添加新节点数据
         */
        const addNodeChangeHandler = (node: ProcessNodeListItem, newNode: {type: 'condition' | 'node' | 'code' | 'message'}) => {
            let ids = uuid()

            const createTemplateNode = (type: NodeTypeEnum, uniqueId: string, newNodeType?: string) => {
                const template: ProcessNodeListItem = {
                    type,
                    name: '',
                    content: '',
                    children: [],
                    id: '',
                    uniqueId,
                    options: {},
                    parentNode: null
                };
                // 新建添加条件节点的时候，该节点options配置对象里添加一个属性conditionList
                if (type === NodeTypeEnum.CONDITION_NODE) {
                    template.options = {
                        conditionList: []
                    }
                }
                if (newNodeType && (newNodeType === 'code' || newNodeType === 'message')) {
                    template.options.type = newNodeType;
                }
                // 默认如果当前类型是条件节点或消息节点默认校验通过
                if (newNodeType && (newNodeType === 'condition' || newNodeType === 'message')) {
                    template.options.requiredCheck = true
                }
                return template;
            };
        
            const templateCondiation = createTemplateNode(NodeTypeEnum.CONDITION, `condition-${ids}`);
            const templateCondiationNode = createTemplateNode(NodeTypeEnum.CONDITION_NODE, ids, newNode.type);
            const templateNode = createTemplateNode(NodeTypeEnum.NODE, ids, newNode.type);

            const _targetNode = findNodeById(node.uniqueId, chartList.value);
            if (!_targetNode) return
            // 存在拷贝一份，防止引用类型导致的错误
            const targetNode = _.cloneDeep(_targetNode);
            const {children, ...rest} = targetNode
            if (rest.parentNode && Object.keys(rest.parentNode).length) {
                rest.parentNode = null;
            }
            if (newNode.type !== NodeTypeEnum.CONDITION) {
                templateNode.children = targetNode.children
                templateNode.parentNode = rest

                if (Array.isArray(targetNode.children) && targetNode.children.length > 0) {
                    const { children , ...rest} = templateNode
                    templateNode.children.forEach(item => {
                      item.parentNode = { ...rest, parentNode: null}  
                    })
                }

                _targetNode.children = [templateNode]

            } else {
                // 如果当前节点的子节点存在condition则直接添加，如果没有需要在创建条件节点的同时生成condition来包裹条件节点
                if (targetNode?.children.some(item => item.type === NodeTypeEnum.CONDITION)) {
                    const {children, ...noChildrenObj} = targetNode.children[0]
                    if (Reflect.has(noChildrenObj, 'parentNode') && noChildrenObj.parentNode) {
                        noChildrenObj.parentNode = null
                    }
                    templateCondiationNode.parentNode = noChildrenObj
                    // 将条件节点直接放到condiation包裹下面的children的数组后面
                    _targetNode.children[0]?.children.push(templateCondiationNode)
                } else {
                    templateCondiationNode.children = targetNode.children
                    templateCondiation.parentNode = rest
                    
                    if (Array.isArray(templateCondiationNode.children) && templateCondiationNode.children.length > 0) {
                        const { children , ...rest} = templateCondiationNode
                        templateCondiationNode.children.forEach(item => {
                          item.parentNode = { ...rest, parentNode: null}  
                        })
                    }

                    templateCondiationNode.parentNode = _.cloneDeep({...templateCondiation, parentNode: null})

                    templateCondiation.children.push(templateCondiationNode)
                    _targetNode.children = [templateCondiation]
                }
            }
        }

        /**
         * @description 通过uniqueId查找指定节点
         * @param id 
         * @param nodes 
         */
        function findNodeById(id: string, nodes: ProcessNodeListItem[]): ProcessNodeListItem | null {
            for (let node of nodes) {
                if (node.uniqueId === id) {
                    return node;
                }
                if (node.children && node.children.length > 0) {
                    const foundNode = findNodeById(id, node.children);
                    if (foundNode) {
                        return foundNode;
                    }
                }
            }
            return null;
        }

        /**
         * @description 查找当前节点的父节点
         * @param id 要查找的节点的id
         * @param nodes 查找数据源
         * @param parent 当前节点的父节点 （暂不需要
         */
        function findParentNodeById(id: string, nodes: ProcessNodeListItem[], parent: ProcessNodeListItem | null = null): ProcessNodeListItem | null {
            for (let node of nodes) {
                if (node.children && node.children.some(child => child.uniqueId === id)) {
                    return node;
                }
                if (node.children && node.children.length > 0) {
                    const foundParent = findParentNodeById(id, node.children, node);
                    if (foundParent) {
                        return foundParent;
                    }
                }
            }
            return null;
        }
        
        /**
         * @description 删除节点逻辑
         * @param node 当前节点数据
         * @param mode 删除当前数据模式
         */
        const deleteNodeChangeHandler = (node: ProcessNodeListItem, mode: deleteMode) => {
            const { uniqueId, type } = node
            const _nodeT = getNodeType(node) // 当前节点类型
            const targetNode = findNodeById(uniqueId, chartList.value)
            const targetNodeParent = findParentNodeById(uniqueId, chartList.value)
            if (!targetNode || !targetNodeParent) return
          
            if (mode === 'all') {
                const parentParentNodeUniqueId = targetNodeParent.uniqueId
                if (node.type === NodeTypeEnum.CONDITION_NODE) {
                    if (targetNodeParent.children.length >1) {
                        targetNodeParent.children = targetNodeParent.children.filter(child => child.uniqueId !== targetNode.uniqueId);
                    } else{
                        const parentNode = findParentNodeById(parentParentNodeUniqueId, chartList.value)
                        if (parentNode) {
                            parentNode.children = []
                        }
                    }
                    return
                }
                targetNodeParent.children = targetNodeParent.children.filter(child => child.uniqueId !== targetNode.uniqueId);
            }
            if (mode === 'current') {
                const { parentNode, children: nodeChildren } = node
                // @ts-ignore
                if (node.type === NodeTypeEnum.NODE) {
                    if (nodeChildren.length === 0) {
                        targetNodeParent.children = targetNodeParent.children.filter(child => child.uniqueId !== targetNode.uniqueId);
                        return
                    }
                    if (parentNode?.type === NodeTypeEnum.NODE || parentNode?.type === NodeTypeEnum.START_NODE) {
                        const { children, ...rest} = targetNodeParent
                        rest.parentNode = null
                        const child = targetNode.children[0]
                        child.parentNode = rest
                        // 如果当前节点是执行动作则清空下面数据，否则不请客
                        let clearOptionsChild = ([NodeTypeEnum.NODE].includes(_nodeT) ? clearCurrentNodeOptions(child) : child);
                        targetNodeParent.children = [clearOptionsChild]
                    }
                    if (parentNode?.type === NodeTypeEnum.CONDITION_NODE) {
                        if (nodeChildren[0].type !== NodeTypeEnum.CONDITION) {
                            const { children, ...rest} = targetNodeParent
                            rest.parentNode = null
                            const child = targetNode.children[0]
                            child.parentNode = rest
                            // 如果当前节点是执行动作则清空下面数据，否则不请客
                            let clearOptionsChild = ([NodeTypeEnum.NODE].includes(_nodeT) ? clearCurrentNodeOptions(child) : child);
                            targetNodeParent.children = [clearOptionsChild]
                        }
                        if (nodeChildren[0].type === NodeTypeEnum.CONDITION) {
                            targetNodeParent.children = []
                        }
                    }
                    return
                }
                if (node.type === NodeTypeEnum.CONDITION_NODE) {
                    if (nodeChildren.length > 0) {
                        const parentNodeId = parentNode.uniqueId
                        const parentParentNode = findParentNodeById(parentNodeId, chartList.value)
                        if (!parentParentNode) return
                        const { children, ...rest } = parentParentNode
                        rest.parentNode = null
                        const childConditionGroupInConditionNode = targetNode.children[0]
                        childConditionGroupInConditionNode.parentNode = rest
                        // let clearOptionsChild = clearCurrentNodeOptions(childConditionGroupInConditionNode)
                        parentParentNode.children = [childConditionGroupInConditionNode]
                    } else {
                        const parentParentNodeUniqueId = targetNodeParent.uniqueId
                        if (targetNodeParent.children.length >1) {
                            targetNodeParent.children = targetNodeParent.children.filter(child => child.uniqueId !== targetNode.uniqueId);
                        } else{
                            const parentNode = findParentNodeById(parentParentNodeUniqueId, chartList.value)
                            if (parentNode) {
                                parentNode.children = []
                            }
                        }
                    }
                    
                }
            }
        }

        /**
         * @description 清空当前节点下面的options
         * @param data 
         */ 
        const clearCurrentNodeOptions = (data: ProcessNodeListItem) => {
            if (!data) return null;
        
            const clearOptions = (node: ProcessNodeListItem) => {
                if ([NodeTypeEnum.NODE].includes(getNodeType(node))) {
                    node.options = {};
                    // TODO 也可以不清除父节点的options，目前没什么用，只用到了uniqueId
                    // if (node.parentNode) {
                    //     node.parentNode.options = {}
                    // }
                }
                if ([NodeTypeEnum.CONDITION_NODE].includes(getNodeType(node))) {
                    node.options = {
                        conditionList: []
                    }
                    node.content = ''
                }
                
                if (node.children && node.children.length > 0) {
                    node.children.forEach(child => clearOptions(child));
                }
            };
        
            const dataCopy = _.cloneDeep(data);
        
            clearOptions(dataCopy);
        
            return dataCopy;
        };

        /**
         * @description 更新节点逻辑
         * @param nodeId 
         * @param newNode 
         */
        const updateNodeChangeHandler = (nodeId: string, newNode: any) => {
            let findUpdateNodeInfo = findNodeById(nodeId, chartList.value)
            if (!findUpdateNodeInfo) return
            findUpdateNodeInfo = newNode
            // Object.assign(findUpdateNodeInfo, newNode)
        }

        /**
         * @description 获取除自己以外父级节点 apiId 数组数据（不含 message 和 code）
         * @param node 当前节点信息
         * @param chartList 当前流程图数据
         */
        const getParentApiIds = (node: ProcessNodeListItem, chartList: ProcessNodeListItem[]): string[] => {
            let validApiIds: (string | null)[] = [];
        
            function traverseParent(id: string | undefined) {
                if (!id) return;
        
                const node = findNodeById(id, chartList);
                if (!node) return;
        
                if ((getNodeType(node) === 'condition-node' || getNodeType(node) === 'condition')) {
                    traverseParent(node?.parentNode?.uniqueId);
                    return
                }

                if (getNodeType(node) === 'code' || getNodeType(node) === 'message') {
                    traverseParent(node?.parentNode?.uniqueId);
                    return
                }

                validApiIds.push(node.options.apiId);
        
                traverseParent(node?.parentNode?.uniqueId);
            }
        
            traverseParent(node?.parentNode?.uniqueId);
        
            return validApiIds;
        };
        
        /**
         * @description 创建触发器
         */
        const createTriggerHandler = async () => {
            try {
                // 这里是了防止当前点击的节点是消息节点的时候直接保存没传给后端
                await validateMessageNode()
                if (!chartList.value || chartList.value.length === 0) {
                    console.warn("请先添加节点")
                    return
                }
                state.buttonStatus = true
                // 创建之前先校验
                validateHandler()
                
                // 先校验首节点
                const startNodeValiRes = validateStartNode(chartList.value[0])
                if (!startNodeValiRes) return

                const {errNode, errCondition} = validatedResult(chartList.value[0]?.children)
                if (errNode && errNode === errCondition) {
                    message.error(`执行动作未填写`)
                    return
                }
                if (errNode > 0) {
                  message.error(`发现有 ${errNode} 个配置错误,请修复完成后保存`)
                  return
                }
                let msg = convertProcessCanvasDataForServer(chartList.value)
                if (msg && msg.executeWay) {
                    Object.assign(msg.executeWay, state.executeWay);
                    msg.name = state.currentTriggerInfo.name;
                    msg.remarks = state.currentTriggerInfo.remarks
                }
                // 如果存在前后不兼容数据，则进行兼容处理
                if (state._compatibilityList.length > 0) {
                    // @ts-ignore
                    compatibility(msg, state._compatibilityList)
                }
                const res = await createTrigger(msg)
                if (!res.success) {
                    message.error(res.message)
                    return
                }
                message.success('创建成功')
                goTriggerIdDetail(res.data.triggerId)
                refreshTab()
            } catch (error) {
                console.error(error)
            } finally {
                state.buttonStatus = false
            }
        }

        /**
         * @description 刷新当前tab
         */
        const refreshTab = () => {
            platform.refreshTab(window.frameElement.getAttribute('fromId'));
        }
        const goTriggerIdDetail = (triggerId: string) => {
            const fromId = window.frameElement.getAttribute('id') || ''
            openAccurateTab({
                type: PageRoutesTypeEnum.PageTriggerDesign,
                params: `triggerId=${triggerId}`,
                fromId
            })
        }

        /**
         * @description 编辑触发器
         */
        const editTriggerHandler = async () => {
            try {
                // 这里是了防止当前点击的节点是消息节点的时候直接保存没传给后端
                await validateMessageNode()
                if (!chartList.value || chartList.value.length === 0) {
                    console.warn("请先添加节点")
                    return
                }
                state.buttonStatus = true
                // 创建之前先校验
                validateHandler()

                // 先校验首节点
                const startNodeValiRes = validateStartNode(chartList.value[0])
                if (!startNodeValiRes) return
                const {errNode, errCondition} = validatedResult(chartList.value[0]?.children)
                if (errNode && errNode === errCondition) {
                    message.error(`执行动作未填写`)
                    return
                }
                if (errNode > 0) {
                  message.error(`发现有 ${errNode} 个配置错误,请修复完成后保存`)
                  return
                }

                let msg = convertProcessCanvasDataForServer(chartList.value, serverData.value)
                if (msg && msg.executeWay) {
                    Object.assign(msg.executeWay, state.executeWay);
                    msg.name = state.currentTriggerInfo.name;
                }
                // 如果存在前后不兼容数据，则进行兼容处理
                if (state._compatibilityList.length > 0) {
                    // @ts-ignore
                    compatibility(msg, state._compatibilityList)
                }
                const res = await editTrigger(msg)
                if (!res.success) {
                    message.error(res.message || '保存错误')
                    return
                }
                const fromId = window.frameElement.getAttribute('id') || ''
                message.success('保存成功')
                openAccurateTab({
                    type: PageRoutesTypeEnum.PageTriggerDesign,
                    params: `triggerId=${res.data.triggerId}&timestamp=${new Date().getTime()}`,
                    fromId
                })
                refreshTab()
            } catch (error) {
                console.error(error)
            } finally {
                state.buttonStatus = false
            }
        }

        /**
         * @description 查到当前节点上所有父节点数据的节点id
         * @param nodeId 节点id
         */
        const findParentApiList = (nodeId: string) => {
            const currentNode = findNodeById(nodeId, chartList.value)
            if (!currentNode) return
            const resList = getParentApiIds(currentNode, chartList.value)
            // @ts-ignore
            state.parentNodeApiIdList = resList
        }

        /**
         * @description 校验函数
         */
        const validateHandler = () => {
          if (!chartList.value || chartList.value.length === 0) {
            console.warn('请先添加节点');
            return;
          }
          runVail(chartList.value[0]?.children, currentCtx)
        }

        /**
         * @description 初始化第二个节点
         */
        const initSecondNode = () => {
            const {children, ...rest} = chartList.value[0]
            chartList.value[0].children.push({
                "type": NodeTypeEnum.NODE,
                "name":  "",
                "content": "",
                "children": [

                ],
                "uniqueId": executeUuid,
                "id": '',
                "options": {
                    "requiredCheck": true
                },
                "parentNode": rest
            })
        }
        /**
         * @description 添加结束节点
         */
        const addEndNode = () => {
            chartList.value.push({
                type: NodeTypeEnum.END_NODE,
                name: '',
                content: '',
                uniqueId: 'end',
                id: 'end',
                children: [],
                options: {}
            })
        }
        initSecondNode()
        addEndNode()


        /**
         * @des 相关校验对应的消息节点事件（比如有没有填写等）
         * @returns {any}
         */
        const validateMessageNode = async ()=> {
            return new Promise((resolve, reject)=> {
                try {
                    if(currentNodeType() === 'message') {
                        if(state.currentSelectNodePanelContentRef) {
                            return (state.currentSelectNodePanelContentRef as unknown as any)?.saveData()
                                .then(()=> {
                                    resolve(true)
                                }).catch(()=> reject(false))
                        }
                    }   
                    resolve(true)
                } catch (error) {
                    reject(error)
                }
            })
        }       

        /**
         * @description 清除当前节点状态数据
         */
        const clearCurrentNodeStateData = async () => {
                try {
                    await validateMessageNode()
                    state.data.changeOpenPanel = false
                    state.currentSelectNode = ''
                    currentCtx.$eventBus.$emit('trigger-design-validate')
                } catch (error) {
                    console.log(error)
                }
        }

        /**
         * @description 获取当前节点类型
         * @param nodeData 
         */
        // const getNodeType = (nodeData: ProcessNodeListItem) => {
        //     if(['code', 'message'].includes(nodeData.options?.apiId)){
        //         return nodeData.options?.apiId 
        //     }
        //     return nodeData.options?.type || nodeData.type
        // }
        /**
         * @description 简单封装查找到的的节点中的当前节点类型
         */
        const currentNodeType = () => {
            if (!state.currentSelectNode) return
            const currentNode = findNodeById(state.currentSelectNode, chartList.value)
            if (!currentNode) return
            return getNodeType(currentNode) || ''
        }

        const handlerClickOutSide = (e: MouseEvent) => {
            const whiteDom = ['.trigger-config-panel', '.process-node-normal__box-wrap', '.range-scale', '.temp-textarea','.layx-window', '.el-message-box']
            if (!whiteDom.some(selector => e.target.closest(selector))) {
                clearCurrentNodeStateData()
            }

        }

        /**
         * @des 处理相关节点点击事件
         * @param {any} newNode:ProcessNodeListItem
         * @param {any} oldNode:ProcessNodeListItem
         * @returns {any}
         */
        const handleNodeClick = async (newNode: ProcessNodeListItem, oldNode: ProcessNodeListItem)=> {
            if(getNodeType(oldNode) === 'message') {
                try {
                    const params = await (state.currentSelectNodePanelContentRef as unknown as any)?.setOnlyMessageParams()
                    params.isEditMessage = true
                    oldNode.options = {
                        ...oldNode.options,
                        apiId: 'message',
                        fieldOptions: params,
                    }
                } catch (error) {
                    console.error('[setOnlyMessageParams error]', error)
                }
            }
        }


        onMounted(() => {
            // document.addEventListener('click', handlerClickOutSide)
            document.querySelector('.trigger-design-box')?.addEventListener('click', handlerClickOutSide)
            currentCtx?.$eventBus.$on('trigger-design-addNodeChange', (node: ProcessNodeListItem, newNode: any) => {
                addNodeChangeHandler(node, newNode)
            })
            currentCtx?.$eventBus.$on('trigger-design-deleteNodeChange', (node: ProcessNodeListItem, mode: deleteMode) => {
                deleteNodeChangeHandler(node, mode)
            })
            currentCtx?.$eventBus.$on('trigger-design-updateNodeChange', (nodeId: string, newNode: any) => {
                updateNodeChangeHandler(nodeId, newNode)
            })
            currentCtx?.$eventBus.$on('trigger-design-node-click', async (nodeId: string, newNode: ProcessNodeListItem , oldNode: ProcessNodeListItem) => {
                if(![NodeTypeEnum.START_NODE, NodeTypeEnum.CONDITION].includes(newNode.type as unknown as NodeTypeEnum)) {
                    findParentApiList(nodeId)
                }
                // 处理相关节点点击value事件 (节点的点击事件都可以放下面事件中处理)
                handleNodeClick(newNode, oldNode)
                
            })
            currentCtx.$eventBus.$on('trigger-design-save', () => {
                createTriggerHandler()
            })
            currentCtx.$eventBus.$on('trigger-design-update', () => {
                editTriggerHandler()
            })
            currentCtx.$eventBus.$on('trigger-design-validate', () => {
                // TODO 校验功能以后可以优化 每个节点都会触发，这是不理智的
                validateHandler()
            })
        })

        onBeforeUnmount(() => {
            document.removeEventListener('click', handlerClickOutSide)
            currentCtx?.$eventBus.$off('trigger-design-addNodeChange')
            currentCtx?.$eventBus.$off('trigger-design-deleteNodeChange')
            currentCtx?.$eventBus.$off('trigger-design-updateNodeChange')
            currentCtx?.$eventBus.$off('trigger-design-node-click')
            currentCtx?.$eventBus.$off('trigger-design-save')
            currentCtx?.$eventBus.$off('trigger-design-update')
            currentCtx?.$eventBus.$off('trigger-design-validate')
        })
        return ()=> (
            <div class="process-node-chart">
                <div class="process-node-chart__content" style={{paddingLeft: '60px'}}>
                    {
                        chartList.value.map(item=> {
                            return  (
                                <MainNodeProcessWrap 
                                    nodeIndex={1}
                                    nodeData={item}
                                    nodeList={chartList.value}
                                />
                            )
                        })
                    }
                 </div>
            </div>
        ) as unknown as VNode
    }
})